// pages/address/address.js
import { addressApi } from '../../utils/api.js'
import { checkLoginAndRedirect } from '../../utils/auth.js'
import { formatAddress } from '../../utils/format.js'

const app = getApp()

Page({
  data: {
    loading: true,
    addresses: [],
    selectedAddressId: null,
    fromOrder: false // 是否来自订单页面
  },

  onLoad(options) {
    // 检查是否来自订单页面
    if (options.from === 'order') {
      this.setData({ fromOrder: true })
    }
    
    this.loadAddresses()
  },

  onShow() {
    // 每次显示时重新加载地址数据
    this.loadAddresses()
  },

  onPullDownRefresh() {
    this.loadAddresses()
  },

  // 加载地址列表
  async loadAddresses() {
    if (!checkLoginAndRedirect()) {
      this.setData({ loading: false })
      return
    }

    try {
      this.setData({ loading: true })
      
      const res = await addressApi.getList()
      
      if (res.code === 1) {
        const addresses = res.data || []
        this.setData({
          addresses,
          selectedAddressId: addresses.find(addr => addr.isDefault === 1)?.id || null
        })
      }
    } catch (error) {
      console.error('加载地址列表失败:', error)
      wx.showToast({
        title: '加载失败',
        icon: 'none'
      })
    } finally {
      this.setData({ loading: false })
      wx.stopPullDownRefresh()
    }
  },

  // 选择地址
  selectAddress(e) {
    if (!this.data.fromOrder) return
    
    const addressId = e.currentTarget.dataset.id
    this.setData({
      selectedAddressId: addressId
    })
  },

  // 确认选择地址
  confirmSelection() {
    if (!this.data.selectedAddressId) {
      wx.showToast({
        title: '请选择地址',
        icon: 'none'
      })
      return
    }
    
    const selectedAddress = this.data.addresses.find(addr => addr.id === this.data.selectedAddressId)
    
    // 返回上一页并传递选中的地址
    const pages = getCurrentPages()
    const prevPage = pages[pages.length - 2]
    
    if (prevPage && prevPage.setSelectedAddress) {
      prevPage.setSelectedAddress(selectedAddress)
    }
    
    wx.navigateBack()
  },

  // 新增地址
  addAddress() {
    wx.navigateTo({
      url: '/pages/address-edit/address-edit'
    })
  },

  // 编辑地址
  editAddress(e) {
    const addressId = e.currentTarget.dataset.id
    wx.navigateTo({
      url: `/pages/address-edit/address-edit?id=${addressId}`
    })
  },

  // 删除地址
  async deleteAddress(e) {
    const addressId = e.currentTarget.dataset.id
    const address = this.data.addresses.find(addr => addr.id === addressId)
    
    if (!address) return
    
    wx.showModal({
      title: '确认删除',
      content: `确定要删除"${address.consignee}"的地址吗？`,
      success: async (res) => {
        if (res.confirm) {
          try {
            wx.showLoading({ title: '删除中...' })
            
            const deleteRes = await addressApi.delete(addressId)
            
            if (deleteRes.code === 1) {
              wx.showToast({
                title: '删除成功',
                icon: 'success'
              })
              // 重新加载地址列表
              this.loadAddresses()
            } else {
              throw new Error(deleteRes.msg || '删除失败')
            }
          } catch (error) {
            console.error('删除地址失败:', error)
            wx.showToast({
              title: error.message || '删除失败',
              icon: 'none'
            })
          } finally {
            wx.hideLoading()
          }
        }
      }
    })
  },

  // 设置默认地址
  async setDefaultAddress(e) {
    const addressId = e.currentTarget.dataset.id
    
    try {
      wx.showLoading({ title: '设置中...' })
      
      const res = await addressApi.setDefault({ id: addressId })
      
      if (res.code === 1) {
        wx.showToast({
          title: '设置成功',
          icon: 'success'
        })
        // 重新加载地址列表
        this.loadAddresses()
      } else {
        throw new Error(res.msg || '设置失败')
      }
    } catch (error) {
      console.error('设置默认地址失败:', error)
      wx.showToast({
        title: error.message || '设置失败',
        icon: 'none'
      })
    } finally {
      wx.hideLoading()
    }
  },

  // 格式化地址显示
  formatAddressDisplay(address) {
    return formatAddress(address)
  }
})
